package DataBase;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import common.Tables.Table;

/**
 * abstract class of the Data base - any class that want to implements 
 * 			the functionality of the database(add,remove,update from tables) must implements it! 
 * @author Orit
 *
 */
public abstract class DataBase {
	SessionFactory sessionFactory;
	Session session;
	
	
	/**
	 * open session 
	 * if the session is close open the session 
	 */
	public void openSession(){
		if (sessionFactory==null){
			sessionFactory = new Configuration().configure().buildSessionFactory(); 
		}
		if (session == null){
			session = sessionFactory.openSession();
			return;
		}
		
		if (!session.isConnected()){
			sessionFactory = new Configuration().configure().buildSessionFactory(); 			
		}
		if (!session.isOpen()){
			session = sessionFactory.openSession();
		}
	}
	
	/**
	 * method gets a query and returns all records regarding this query.
	 * @param query
	 * @return
	 */
	protected List<Table> generalQuery(String query){
		
		Query queryObject = session.createQuery(query);
		List<Table> objList = queryObject.list();
		Iterator<Table> it = objList.iterator();
		Object obj;
		while (it.hasNext()){
			obj=it.next();
			session.refresh(obj);		
		}
		return objList;		
	}
		
}
